
//  KFDSetBankAccountViewControllerTableViewController.m
//  KFD
//
//  Created by JIRENTIANXIANG on 7/21/15.
//  Copyright © 2015 kfd. All rights reserved.
//

#import "KFDSetBankAccountViewController.h"
#import "KFDUIConfigurator.h"
#import "UIPopoverListView.h"
#import "KFDClient.h"
#import "ui_config.h"
#import "DoImagePickerController.h"
#import "KFDAccountManager.h"
#import "JTToast.h"

#define UITableViewCellReuseIdentifier @"UITableViewCell"

@interface KFDSetBankAccountViewController ()<UIPopoverListViewDataSource,UIPopoverListViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong,nonatomic) NSString* frontUrl;
@property (strong,nonatomic) NSString* backUrl;

@property (strong,nonatomic) NSArray* banks;
@property (weak, nonatomic) IBOutlet UILabel *bankLabel;
@property (weak, nonatomic) IBOutlet UITextField *bankAccountNameField;
@property (weak, nonatomic) IBOutlet UITextField *bankAccountNumberField;
@property (weak, nonatomic) IBOutlet UITextField *branchBankField;
@property (weak, nonatomic) IBOutlet UIImageView *uploadFrontPanel;
@property (weak, nonatomic) IBOutlet UIImageView *uploadBackPanel;

@property (strong,nonatomic) UIImagePickerController* frontImagePicker;
@property (strong,nonatomic) UIImagePickerController* backImagePicker;

@end

@implementation KFDSetBankAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    KFDUIConfigurator* uiConfigurator=[KFDUIConfigurator configuratorForViewController:self];
    [uiConfigurator configureNavigationBarWithBackAction:@selector(goBack)];
    self.title=@"完善银行信息";

    UITapGestureRecognizer* frontTapRecog=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadFrontPanelTapped)];
    [self.uploadFrontPanel addGestureRecognizer:frontTapRecog];
    self.uploadFrontPanel.userInteractionEnabled=YES;
    
    UITapGestureRecognizer* backTapRecog=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadBackPanelTapped)];
    [self.uploadBackPanel addGestureRecognizer:backTapRecog];
    self.uploadBackPanel.userInteractionEnabled=YES;
    
    self.frontImagePicker=[[UIImagePickerController alloc] init];
    self.frontImagePicker.delegate=self;
    
    self.backImagePicker=[[UIImagePickerController alloc] init];
    self.backImagePicker.delegate=self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageSizeExceedLimit) name:KFDImageSizeExceedLimitNotification object:nil];
}

-(void)imageSizeExceedLimit
{
    [[JTToast makeText:@"图片大小超过限制"] showInView:self.view size:CGSizeMake(160, 40)];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KFDImageSizeExceedLimitNotification object:nil];
}

-(void)uploadFrontPanelTapped
{
    UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* chooseFromAlbum=[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.frontImagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.frontImagePicker animated:YES completion:nil];
    }];
    [alertController addAction:chooseFromAlbum];
    UIAlertAction* takePhoto=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.frontImagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.frontImagePicker animated:YES completion:nil];
    }];
    [alertController addAction:takePhoto];
    UIAlertAction* cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alertController addAction:cancel];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)uploadBackPanelTapped
{
    UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* chooseFromAlbum=[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.backImagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.backImagePicker animated:YES completion:nil];
    }];
    [alertController addAction:chooseFromAlbum];
    UIAlertAction* takePhoto=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.backImagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.backImagePicker animated:YES completion:nil];
    }];
    [alertController addAction:takePhoto];
    UIAlertAction* cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alertController addAction:cancel];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (IBAction)saveButtonPressed:(id)sender {
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    
    KFDUserAddress* userAddress=accountManager.userAddress;
    KFDBankAccountInfo* bankInfo=[[KFDBankAccountInfo alloc] init];
    bankInfo.bank_name=self.bankLabel.text;
    bankInfo.account=self.bankAccountNameField.text;
    bankInfo.branch=self.branchBankField.text;
    bankInfo.idcard_main=self.frontUrl;
    bankInfo.idcard_side=self.backUrl;
    bankInfo.province=userAddress.province;
    bankInfo.city=userAddress.city;
    bankInfo.district=userAddress.district;
    
    if ([accountManager checkBankAccountInfo:bankInfo illegalInputHandler:^(NSString *message) {
        [[JTToast makeText:message] showInView:self.view size:CGSizeMake(message.length*20, 40)];
    }]) {
        [accountManager setBankAccountInfo:bankInfo successHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [[JTToast makeText:@"保存成功"] showInView:self.view size:CGSizeMake(80, 40)];
                [self.navigationController popViewControllerAnimated:YES];
            });
        } failureHandler:^(KFDResponseBody *response) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[JTToast makeText:response.message] showInView:self.view size:CGSizeMake(response.message.length*20, 40)];
            });
        }];
    }
}

-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-------------------------------------------------------------------------------------
#pragma mark - Table view delegate
//-------------------------------------------------------------------------------------
-(void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row==2) {
        KFDClient* client=[KFDClient sharedClient];
        [client getBanksWithSuccessHandler:^(NSArray *banks) {
            self.banks=banks;
            UIPopoverListView* banksPopoverListView=[[UIPopoverListView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH*0.8, SCREEN_HEIGHT*0.6)];
            banksPopoverListView.center=CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
            banksPopoverListView.datasource=self;
            banksPopoverListView.delegate=self;
            [banksPopoverListView.listView registerClass:[UITableViewCell class] forCellReuseIdentifier:UITableViewCellReuseIdentifier];
            dispatch_async(dispatch_get_main_queue(), ^{
                [banksPopoverListView show];
            });
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
    }
}
//-------------------------------------------------------------------------------------


//-------------------------------------------------------------------------------------
#pragma mark - Popover list view data source
//-------------------------------------------------------------------------------------
-(NSInteger)popoverListView:(UIPopoverListView *)popoverListView numberOfRowsInSection:(NSInteger)section
{
    return self.banks.count;
}
-(UITableViewCell*)popoverListView:(UIPopoverListView *)popoverListView cellForIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell=[popoverListView.listView dequeueReusableCellWithIdentifier:UITableViewCellReuseIdentifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] init];
    }
    cell.textLabel.text=self.banks[indexPath.row];
    return cell;
}
//-------------------------------------------------------------------------------------


//-------------------------------------------------------------------------------------
#pragma mark - Popover list view delegate
//-------------------------------------------------------------------------------------
-(CGFloat)popoverListView:(UIPopoverListView *)popoverListView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}
-(void)popoverListView:(UIPopoverListView *)popoverListView didSelectIndexPath:(NSIndexPath *)indexPath
{
    self.bankLabel.text=self.banks[indexPath.row];
}
//-------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------
#pragma mark - DoImagePickerController delegate
//-------------------------------------------------------------------------------------
//-(void)didCancelDoImagePickerController
//{
//    [self dismissViewControllerAnimated:YES completion:nil];
//}
//-(void)didSelectPhotosFromDoImagePickerController:(DoImagePickerController *)picker result:(NSArray *)aSelected
//{
//    [self dismissViewControllerAnimated:YES completion:nil];
//    UIImage* image=aSelected.firstObject;
//    KFDClient* client=[KFDClient sharedClient];
//    if (picker==self.frontImagePicker) {
//        self.uploadFrontPanel.image=image;
//    }else if (picker==self.backImagePicker){
//        self.uploadBackPanel.image=image;
//    }
//    [client uploadImage:image type:@"idcard" successHandler:^(NSString *url) {
//        if (picker==self.frontImagePicker) {
//            self.frontUrl=url;
//        }else if (picker==self.backImagePicker){
//            self.backUrl=url;
//        }
//    } failureHandler:^(KFDResponseBody *response) {
//        
//    }];
//}
//-------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------
#pragma mark - UIImagePickerController delegate
//-------------------------------------------------------------------------------------
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage* image=info[@"UIImagePickerControllerOriginalImage"];
    KFDClient* client=[KFDClient sharedClient];
    [client uploadImage:image type:@"idcard" successHandler:^(NSString *url) {
        if (picker==self.frontImagePicker) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.frontUrl=url;
                self.uploadFrontPanel.image=image;
            });
        }else if (picker==self.backImagePicker){
            dispatch_async(dispatch_get_main_queue(), ^{
                self.backUrl=url;
                self.uploadBackPanel.image=image;
            });
        }
    } failureHandler:^(KFDResponseBody *response) {
        
    }];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//-------------------------------------------------------------------------------------

@end
